<template>
  <!---搜索表单-->
    <div class="search-div">
        <el-form label-width="70px" size="small">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="关键字">
                        <el-input v-model="queryDto.keyword" style="width: 100%" placeholder="用户名"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="创建时间">
                        <el-date-picker v-model="createTimes" type="daterange" range-separator="To"
                                        start-placeholder="开始时间"
                                        end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row style="display:flex">
                <el-button type="primary" size="small" @click="searchSysUser"> 搜索</el-button>
                <el-button size="small" @click="resetData">重置</el-button>
            </el-row>
        </el-form>
    </div>

  <!--添加按钮-->
    <div class="tools-div">
        <el-button type="success" size="small" @click="addShow">添 加</el-button>
    </div>

    <el-dialog v-model="dialogVisible" title="添加或修改" width="30%" @close="handleDialogClose">
        <el-form label-width="100px">
            <el-form-item label="用户名">
                <el-input v-model="sysUser.username" :disabled="disabled"/>
            </el-form-item>
            <el-form-item v-if="sysUser.id == null" label="密码">
                <el-input type="password" show-password v-model="sysUser.password"/>
            </el-form-item>
            <el-form-item label="手机">
                <el-input v-model="sysUser.mobile"/>
            </el-form-item>
            <el-form-item label="邮箱">
                <el-input v-model="sysUser.email"/>
            </el-form-item>
            <el-form-item label="头像">
                <el-upload class="avatar-uploader"
                           :before-upload="beforeAvatarUpload"
                           action="http://106.119.162.97/school/admin/system/fileUpload"
                           :show-file-list="false"
                           :on-success="handleAvatarSuccess" :headers="headers">
                    <img v-if="sysUser.avatar" :src="sysUser.avatar" class="avatar"/>
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus/>
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submit">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

  <!---数据表格-->
    <el-table :data="list" style="width: 100%" border>
        <el-table-column prop="username" label="用户名" min-width="150px"/>
        <el-table-column prop="mobile" label="手机" min-width="150px"/>
        <el-table-column prop="email" label="邮箱" width="230px"/>
        <el-table-column prop="avatar" label="头像" #default="scope">
            <img :src="scope.row.avatar" width="50"/>
        </el-table-column>
        <el-table-column prop="userStatus" label="状态" #default="scope" width="80px" align="center">
            <el-switch v-model="scope.row.status" :active-value="1"
                       :inactive-value="0" class="ml-2" style="--el-switch-on-color: #13ce66;"
                       @change="handleChange(scope.row)"/>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最近登录时间" width="160px" align="center"/>
        <el-table-column prop="ipconf" label="最近登录地址" width="160px" align="center"/>
        <el-table-column prop="createTime" label="创建时间" width="160px" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" width="160px" align="center"/>
        <el-table-column label="操作" align="center" width="240" #default="scope" fixed="right">
            <el-button type="primary" size="small" @click="editSysUser(scope.row)"> 修改</el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row)"> 删除</el-button>
            <el-button type="warning" size="small" @click="showAssignRole(scope.row)"> 分配角色</el-button>
        </el-table-column>
    </el-table>

    <el-dialog v-model="dialogRoleVisible" title="分配角色" width="40%">
        <el-form label-width="80px">
            <el-form-item label="用户名">
                <el-input disabled :value="sysUser.username"></el-input>
            </el-form-item>
            <el-form-item label="角色列表">
                <el-checkbox-group v-model="userRoleIds">
                    <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id"> {{ role.name }}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item>
                <!-- 分配角色表单提交按钮添加doAssign事件处理函数 -->
                <el-button type="primary" @click="doAssign">提交</el-button>
                <el-button @click="dialogRoleVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-pagination v-model:current-page="pageParams.page" v-model:page-size="pageParams.limit"
                   :page-sizes="[5, 10, 20, 50, 100]" @size-change="fetchData" @current-change="fetchData"
                   layout="total, sizes, prev, pager, next" :total="total"/>
</template>

<script setup>
import {useApp} from '@/pinia/modules/app'
import {onMounted, ref} from 'vue'
import {
    DeleteSysUserById,
    DoAssignRoleToUser,
    GetSysUserListByPage,
    SaveSysUser,
    UpdateSysUser,
    UpdateSysUserStatus
} from '@/api/sysUser'
import {ElMessage, ElMessageBox} from 'element-plus'
import {GetAllRoleList} from '@/api/sysRole'

// 角色列表
const userRoleIds = ref([])
const allRoles = ref([])
const dialogRoleVisible = ref(false)

const showAssignRole = async row => {
    sysUser.value = row
    dialogRoleVisible.value = true
    // 查询所有的角色数据
    const {data} = await GetAllRoleList(row.id)
    allRoles.value = data.allRolesList
    // 获取当前登录用户的角色数据
    userRoleIds.value = data.sysUserRoles
}

// 角色分配按钮事件处理函数
const doAssign = async () => {
    let assginRoleVo = {
        userId: sysUser.value.id,
        roleIdList: userRoleIds.value,
    }
    const {code, message, data} = await DoAssignRoleToUser(assginRoleVo)
    if (code === 200) {
        ElMessage.success('操作成功')
        dialogRoleVisible.value = false
        await fetchData()
    }
}

const headers = {
    token: useApp().authorization.token, // 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
}

const beforeAvatarUpload = (file) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 1;
    if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 1MB!');
    }
    return isJPG && isLt2M;
}
// 图像上传成功以后的事件处理函数
const handleAvatarSuccess = (response) => {
    if (response.code === 200) {
        ElMessage.success('上传成功')
        sysUser.value.avatar = response.data
    } else {
        ElMessage.error('上传失败！')
    }
}

// 删除用户
const deleteById = row => {
    ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const {code} = await DeleteSysUserById(row.id)
        if (code === 200) {
            ElMessage.success('删除成功')
            await fetchData()
        }
    })
}

const disabled = ref(false)

// 修改按钮点击事件处理函数
const editSysUser = row => {
    disabled.value = true
    dialogVisible.value = true
    sysUser.value = row
}

// 表格数据模型
const list = ref([])

// 分页条数据模型
const total = ref(0)

// 定义搜索表单数据模型
const queryDto = ref({
    keyword: '',
    createTimeBegin: '',
    createTimeEnd: '',
})
const createTimes = ref([])

//分页数据
const pageParamsForm = {
    page: 1, // 页码
    limit: 10, // 每页记录数
}
const pageParams = ref(pageParamsForm)

// onMounted钩子函数
onMounted(() => {
    fetchData()
})

// 搜素按钮点击事件处理函数
const searchSysUser = () => {
    fetchData()
}

// 重置按钮点击事件处理函数
const resetData = () => {
    queryDto.value = {}
    createTimes.value = []
}
//状态改变
const handleChange = async row => {
    // 这里发起一个异步请求来更新用户状态
    const {code, message} = await UpdateSysUserStatus(row.id, row.status)
    if (code === 200) {
        ElMessage.success(message)
    }
}

// 定义分页查询方法
const fetchData = async () => {
    if (createTimes.value.length === 2) {
        queryDto.value.createTimeBegin = createTimes.value[0]
        queryDto.value.createTimeEnd = createTimes.value[1]
    }
    // 请求后端接口进行分页查询
    const {data} = await GetSysUserListByPage(pageParams.value.page, pageParams.value.limit, queryDto.value)
    list.value = data.list
    total.value = data.total
}

// 添加表单对话框显示隐藏控制变量
const dialogVisible = ref(false)

const addShow = () => {
    disabled.value = false
    sysUser.value = {}
    dialogVisible.value = true
}

// 定义提交表单数据模型
const defaultForm = {
    username: '',
    mobile: '',
    email: '',
    avatar: '',
    description: '',
}
const sysUser = ref(defaultForm)
//重置表单数据
const handleDialogClose = () => {
    sysUser.value = {...defaultForm}
}
// 提交按钮事件处理函数
const submit = async () => {
    if (!sysUser.value.id) {
        const {code, message, data} = await SaveSysUser(sysUser.value)
        if (code === 200) {
            dialogVisible.value = false
            ElMessage.success('操作成功')
            await fetchData()
        } else {
            ElMessage.error(message)
        }
    } else {
        const {code, message, data} = await UpdateSysUser(sysUser.value)
        if (code === 200) {
            dialogVisible.value = false
            ElMessage.success('操作成功')
            await fetchData()
        } else {
            ElMessage.error(message)
        }
    }
}
</script>

<style scoped>
.search-div {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}

.tools-div {
    margin: 10px 0;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>